<template>
  <BasicModal v-bind="$attrs" @register="register" :title="displayModuleTitle" @ok="onButtonOk">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref, toRaw } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { addOrUpdateFacilitySchema } from './facility.data';
  import { addFacility, updateFacility, getFacility } from '/@/api/ehs/facility';
  export default defineComponent({
    components: { BasicModal, BasicForm },
    emits: ['success'],
    name: 'ImportFacilityModal',
    props: ['unitOption'],
    setup(props, { emit }) {
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const orgcode = ref();
      const dataId = ref();
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: addOrUpdateFacilitySchema,
        showActionButtonGroup: false,
        scrollToFirstError: true,
        actionColOptions: {
          span: 24,
        },
      });
      const [register, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          operateType.value = unrefData.operateType;
          dataId.value = unrefData.dataId;
          orgcode.value = unrefData.orgcode;
          updateSchema({
            field: 'unitid',
            componentProps: {
              getPopupContainer: (triggerNode) => document.body,
              treeData: props.unitOption,
              fieldNames: { label: 'unitname', value: 'unitid', children: 'children' },
              listHeight: 150,
              treeDefaultExpandAll: true, //默认展开
              showCheckedStrategy: 'SHOW_ALL', //定义选中项回填的方式:默认只显示子节点;SHOW_ALL:显示所有选中节点(包括父节点);SHOW_PARENT:只显示父节点(当父节点下所有子节点都选中时).
            },
          });
        }
        if (operateType.value == OperationTypeEnum.EDIT) {
          getFacilityById();
        }
      });

      async function onButtonOk() {
        const values = await validate();
        //根据指定的操作类型分别进行提交数据和处理
        if (operateType.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            //调用接口进行保存
            addFacility({ ...values })
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                setModalProps({ confirmLoading: false });
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (operateType.value == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateFacility({ ...values })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              setModalProps({ confirmLoading: false });
            });
        }
      }

      //操作成功后
      function opSuccess() {
        emit('success');
        closeModal();
      }

      function getFacilityById() {
        getFacility(dataId.value).then((res) => {
          setFieldsValue(res);
        });
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      return {
        register,
        closeModal,
        displayModuleTitle,
        onButtonOk,
        registerForm,
      };
    },
  });
</script>
